import { COMPONENT_TYPES } from '../const/applyForm/targetSet'
import { uuid } from 'vue-uuid'
export const headers = { authorization: localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : '' }
export const findMaxValue = (options) => {
  return options.reduce((maxValue, currentOption) => {
    return Math.max(maxValue, currentOption.value)
  }, -Infinity)
}

const responseFileFn = (response, file) => {
  // 根据响应结果, 设置 URL
  return {
    name: file.name,
    url: URL.createObjectURL(file.raw),
    fileId: response.data
    // size: file.size
  }
}
const responseImgFn = (response, file, imgList) => {
  return {
    name: file.name,
    // url: URL.createObjectURL(file.raw).replace('blob:', ''),
    url: file.url.replace("blob:", ''),
    fileId: response.data,
    imgList
    // size: file.size
  }
}

// 获取表格哪些列存在默认值
export const extractColumnsIndex = (defaultValue) => {
  const res = []
  defaultValue.forEach(obj => {
    const keys = Object.keys(obj)
    keys.forEach(key => {
      if (
        obj[key] !== null &&
        obj[key] !== undefined &&
        obj[key] !== '' &&
        (!(Array.isArray(obj[key]) && obj[key].length < 1)) // 数组的话要有值
      ) {
        res.push(key)
      }  
    })
  })
  // 去重
  return [...new Set(res)]
}
/**
 * 1.解析treeData为动态表单配置
 * 2.给上传附件的配置添加上headers
 * 3. 添加Fn,函数转不了json，只能后期处理加上
 * 4.当查看人查看表单时，附件上传组件需替换为附件展示列表及下载
 * 5.当查看人查看表单时，图片上传组件需替换为图片展示列表及下载
 * 6.表格当某列有值的情况下，该列设置为disable
 * */
export const extractFormDesc = ({treeData, isFn = true, isDetail, disabledColumn}) => {
  const formDesc = {}
  function traverse(nodes) {
    nodes.forEach(node => {
      if (node.formDesc && node.formDesc.length) {
        for (let i = 0; i < node.formDesc.length; i++) {
          const formDescItem = node.formDesc[i]
          // 检查是否需要替换 upload-file 类型的项
          if (isDetail && formDescItem.type === 'upload-file') {
            // 创建一个新的对象，使用 fileListTemplate 的属性，并保留 id
            const newFormDescItem = {
              ...formDescItem,
              type: 'file-list'
            }
            // 替换 formDesc 中的当前项
            formDesc[formDescItem.id] = newFormDescItem
          } else if (formDescItem.type === 'upload-file' && formDescItem.attrs && formDescItem.attrs.headers) {
            // 使用全局headers替换当前的headers,上传附件添加函数，在预览时不添加函数
            formDescItem.attrs.headers = headers
            if (isFn) {
              formDescItem.attrs.responseFn = responseFileFn
            }
          } else if (formDescItem.type === 'image-uploader' && formDescItem.attrs && formDescItem.attrs.headers) {
            // 图片上传控件加headers和函数
            formDescItem.attrs.headers = headers
            formDescItem.attrs.responseFn = responseImgFn
            if (isDetail) {
              formDescItem.attrs.isDetail = true
            }
          } else if (formDescItem.type === 'table-editor' && disabledColumn) {
            // 表格控制列组件disabled
            const indexArr = extractColumnsIndex(formDescItem.default)
            console.log("indexArr", indexArr, formDescItem)
            formDescItem.attrs.columns.forEach(item => {
              if (indexArr.includes(item.prop)) {
                item.content.attrs.disabled = true
              } else {
                item.content.attrs.disabled = false
              }
            })
          }
          // 如果不是替换的情况，则直接将 formDescItem 添加到 formDesc
          if (!isDetail || formDescItem.type !== 'upload-file') {
            formDesc[formDescItem.id] = formDescItem;
          }
        }
      }
      if (node.children) {
        traverse(node.children); // 递归遍历子节点
      }
    })
  }
  traverse(treeData); // 开始遍历
  return formDesc
}

// 单独转成后端需要的参数
export const extractFormDescForFieldMap = (tree) => {
  let fieldMap = {}
  function traverse(node) {
    // 首先检查节点是否有 children 属性，并且 children 是否是数组
    if (Array.isArray(node.children)) {
      node.children.forEach(child => {
        traverse(child); // 递归遍历子节点
      });
    }
    
    // 然后检查节点是否有 formDesc 属性，并且 formDesc 是否是数组
    if (Array.isArray(node.formDesc)) {
      node.formDesc.forEach(desc => {
        // 将type属性转成对应数字
        const descCopy = { ...desc, type: COMPONENT_TYPES[desc.type] }
        // 确保 desc 对象有 id 属性
        if (desc && typeof desc.id !== 'undefined') {
          fieldMap[desc.id] = descCopy; // 将 desc 对象添加到 fieldMap 中
        }
      });
    }
  }
  traverse(tree[0])
  return fieldMap
}

// 转后端id
export const formatParams = (fieldList, formData) => {
  const result = {}
  Object.values(fieldList).forEach(item => {  
    if (formData.hasOwnProperty(item.refId)) {  
      result[item.id] = formData[item.refId];  
    }  
  })
  return result
}

// 反转后端id
export const reFormatParams = (fieldList, formData) => {
  const result = {}
  Object.values(fieldList).forEach(item => {  
    if (formData.hasOwnProperty(item.id)) {  
      result[item.refId] = formData[item.id]
    }  
  })
  return result
}

// 一键导入功能，递归设置formDesc
export const setFormDescRecursively = (node) => {
  const createFormDesc = (label, tip, isLeaf) => {
    const formDescOfNoLeaf = [
      {
        id: uuid.v1(),
        label: "",
        type: "text",
        default: label,
        layout: 23,
        labelWidth: "0",
        class: "title",
        maxlength: 300,
      }
    ]
    if (tip) {
      formDescOfNoLeaf.unshift({
        id: uuid.v1(),
        label: '',
        type: 'tooltip',
        default: tip,
        layout: 1,
        labelWidth: '0',
        attrs: {
          isRight: false // 假设这里总是false，或者应该作为参数传递
        }
      })
    }
    const formDescOfLeaf = [
      {
        id: uuid.v1(),
        type: "input",
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: true,
        attrs: {
          maxlength: 300
        },
      },
      ...(tip ? [{
        id: uuid.v1(),
        label: '',
        type: 'tooltip',
        default: tip,
        layout: 1,
        labelWidth: '0',
        attrs: {
          isRight: false // 假设这里总是false，或者应该作为参数传递
        }
      }] : [{
        id: uuid.v1(),
        label: "",
        labelWidth: "0",
        type: "text",
        default: "",
        layout: 1,
        isShowLabel: false
      }]),
      // {
      //   id: uuid.v1(),
      //   label: "备注",
      //   layout: 9,
      //   type: "input",
      //   attrs: {
      //     maxlength: 300
      //   }
      // }
    ]
    return isLeaf ? formDescOfLeaf : formDescOfNoLeaf
  }
  const attributes = [
    {
      type: 0,
      attrs: {
        maxlength: 300
      },
      control: 1
    },
    {
      type: 0,
      isShow: 0,
      maxlength: 300,
      require: 0,
    },
    {}
  ]
  const isLeaf = node.children.length === 0
  node.formDesc = createFormDesc(node.label, node.tip, isLeaf)
  // 控制换行
  node.formDesc[0].break = true
  if (isLeaf) {
    // 设置指标值默认参数
    node.attributes = attributes
  }
  node.children.forEach(child => {
    setFormDescRecursively(child)
  })
}

